import hashlib
import os
import time
import uuid
from django.conf import settings
from django.core.files.base import ContentFile
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import path
from hot import models
from utils.cos import upload


class BaseCurd(object):
    list_template_name = "manage/list.html"

    def __init__(self, view_list, prefix):
        self.view_list = view_list
        self.prefix = prefix

    def dispatch(self, func):
        def inner(request, *args, **kwargs):
            # self.request = request
            res = func(request, *args, **kwargs)
            return res

        return inner

    @classmethod
    def urls(cls, view_list=None, prefix=None):
        if not view_list:
            view_list = ["list", "add", "edit", "delete"]
        if not prefix:
            prefix = cls.__name__.lower()

        # 实例化对象
        instance = cls(view_list, prefix)
        router = []
        for item in view_list:
            func = getattr(instance, item)
            if item == 'list':
                router.append(path(f'{item}/<int:cid>/', instance.dispatch(func), name=f"{prefix}_{item}"))
                router.append(path(f'{item}/<int:cid>/<int:nid>/', instance.dispatch(func), name=f"{prefix}_{item}"))
            elif item in ["add", 'delete']:
                router.append(path(f'{item}/<int:cid>/', instance.dispatch(func), name=f"{prefix}_{item}"))
            else:
                router.append(path(f'{item}/<int:cid>/<int:nid>/', instance.dispatch(func), name=f"{prefix}_{item}"))

        extra_router = instance.get_extra_url(instance)
        if extra_router:
            router.extend(extra_router)

        return router, None, None

    def get_extra_url(self, obj):
        pass

    def get_queryset(self, request, cid, priority=None):
        pass

    def list(self, request, cid, nid=None):
        queryset = self.get_queryset(request, cid, nid)
        pager = queryset
        context = {
            "pager": pager,
            "url_add_name": f"{self.prefix}_add",
            "url_edit_name": f"{self.prefix}_edit",
            "url_delete_name": f"{self.prefix}_delete",
            "table_header": self.table_header,
            "table_field": self.table_field,
            "nums": self.get_priority_nums(),
            'cid': cid,
            'category': models.Category.objects.filter(id=cid).first()
        }
        print(context)

        return render(request, self.list_template_name, context)

    def add(self, request, cid):
        form_class = self.form_class
        if request.method == "GET":
            category = self.get_category(cid)
            return render(request, 'manage/add.html',
                          {'nums': range(1, category.priority_num + 1), 'op': 'add', 'cid': cid})

        form = form_class(data=request.POST)
        # print(request.POST)
        # print(request.FILES)
        if not form.is_valid():
            return JsonResponse({'code': '-1', 'data': form.errors})

        files = request.FILES.getlist('files')

        # 创建一个新的 ContentManage 实例，并设置其他字段的值
        try:
            new_content_instance = models.ContentManage.objects.create(**form.cleaned_data, content_category_id=cid)

            # 传入文件对象
            for file in files:

                type = file.name.split('.')[-1]
                file.name = hashlib.md5(str(time.time()).encode()).hexdigest() + str(uuid.uuid4()) + '.' + type
                upload(file, file.name)
                if file.content_type.startswith('image'):
                    img_instance = models.ImgModel.objects.create(
                        content_img=ContentFile(file.read(), file.name),
                    )
                    # 对于视频文件，您可能希望直接使用FileField
                elif file.content_type.startswith('video'):
                    img_instance = models.ImgModel.objects.create(
                        content_img=file,
                    )
                new_content_instance.content_imgs.add(img_instance)
                # 保存到cos服务器上面

            return JsonResponse({'code': '200', 'data': '/index/list/'})
        except Exception as e:
            print(e)
            return JsonResponse({'code': '200', 'data': '/index/list/'})

    def get_instance(self, request, nid):
        return self.instance

    def edit(self, request, cid, nid):
        form_class = self.form_class

        if request.method == "GET":
            category = self.get_category(cid)
            form = models.ContentManage.objects.filter(content_id=nid, content_category=cid).first()
            return render(request, 'manage/edit.html',
                          {'nums': range(1, category.priority_num + 1), 'form': form, 'op': 'edit', 'cid': cid})

        form = form_class(data=request.POST)
        if not form.is_valid():
            return JsonResponse({'code': '-1', 'data': form.errors})

        files = request.FILES.getlist('files')
        try:
            content_instance = models.ContentManage.objects.filter(content_id=nid, content_category=cid)

            # 删除文件:
            for img_instance in content_instance.first().content_imgs.all():
                try:
                    img_path = os.path.join(settings.MEDIA_ROOT, img_instance.content_img.name)
                    os.remove(img_path)
                except Exception as e:
                    print(f"Error deleting image file {img_path}: {e}")

            content_instance.first().content_imgs.all().delete()

            content_instance.update(**form.cleaned_data, content_category_id=cid)

            # 为新的实例添加新的图片文件
            for file in files:
                type = file.name.split('.')[-1]
                file.name = hashlib.md5(str(time.time()).encode()).hexdigest() + str(uuid.uuid4()) + '.' + type
                upload(file, file.name)
                img_instance = models.ImgModel.objects.create(
                    content_img=ContentFile(file.read(), file.name),
                )
                content_instance.first().content_imgs.add(img_instance)
                # 保存到cos服务器上面

            return JsonResponse({'code': '200', 'data': '/index/list/'})
        except Exception as e:
            print(e)
        return JsonResponse({'code': '500', 'data': '/index/list/'})

    def delete(self, request, cid):
        index_id = int(request.POST.get('index_id'))
        self.do_delete(request, index_id, cid)
        return JsonResponse({'status': '200', 'data': 'ok'})

    def do_delete(self, request, index_id, cid):
        pass

    def delete_all(self, request, cid):
        pass
